package com.drore.logapp.http.interceptor;

import android.util.Log;

import com.drore.logapp.base.BaseApplication;
import com.drore.logapp.http.HttpCookieLogin;
import com.drore.logapp.utils.SpKeyUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;


/**
 * desc
 *
 * @author sixbing
 * @date 2018/12/11 11:58
 */
public class CheckCookiesInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        if (isExpired(originalResponse)) {

            if (refreshCookies()) {
                Log.e("CheckCookiesInterceptor", "401,if");
                Request.Builder builder = chain.request().newBuilder();
                String preferences = BaseApplication.getSp().getString("request-token", "null");
                builder.addHeader("request-token", preferences);
                return chain.proceed(builder.build());
            } else {
                //跳转登录页面
//                ARouterManager.startLoginModule();
                Log.e("CheckCookiesInterceptor", "401,else");
                return originalResponse;
            }
        } else {
            return originalResponse;
        }

    }

    private boolean refreshCookies() {
        if (!BaseApplication.getSp().getBoolean(SpKeyUtils.IS_AUTO_LOGIN, true)) {
            return false;
        }
        try {
            String uname = BaseApplication.getSp().getString(SpKeyUtils.USER_NAME);
            String password = BaseApplication.getSp().getString(SpKeyUtils.USER_ASS_WORD);
            retrofit2.Response<String> execute = HttpCookieLogin.createHttpClient(uname, password).loginCookie().execute();
            if (execute != null && execute.code() == 200) {
                Log.e("refreshCookies", "refreshCookies success:" + execute.headers().get("request-token"));
                BaseApplication.getSp()
                        .putString(SpKeyUtils.request_token, execute.headers().get("request-token"));
                return true;
            } else {
                Log.e("refreshCookies", "refreshCookies success:" + execute.headers().get("request-token"));
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean isExpired(Response originalResponse) {
        return originalResponse.code() == 401;
    }
}
